package org.example;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.util.EntityUtils;

import java.net.URI;

import static java.lang.Thread.sleep;

public class Main2 {
    // 定义起始位置，默认为0
    public static int start = 0;
    // 定义每页限制的数量，默认为10
    public static int limit = 10;

    public static void main(String[] args) {
        // 计算需要循环的次数，每次获取limit条数据，总共需要获取85802条数据
        for (int i = 0; i < 85802 / limit; i++) {
            // 打印当前的起始序号
            System.out.println("起始序号:" + (start+1));
            try (CloseableHttpClient httpClient = HttpClients.custom()
                    // 设置SSL上下文，信任所有证书
                    .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build())
                    // 设置主机名验证器为NoopHostnameVerifier，不验证主机名
                    .setSSLHostnameVerifier(new NoopHostnameVerifier())
                    .build()) {

                // 构建请求的URI，添加查询参数
                URI uri = new URIBuilder("https://xkz.nfra.gov.cn/bx/WkCXOP/getLicence.do")
                        .addParameter("useState", "3") // 设置useState参数为3
                        .addParameter("start", String.valueOf(start)) // 设置start参数为当前的起始位置
                        .addParameter("limit", String.valueOf(limit)) // 设置limit参数为每页的数量
                        .build();
                // 创建HttpPost请求
                HttpPost post = new HttpPost(uri);
                // 设置User-Agent头
                post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36");
                // 设置Cookie头
                post.setHeader("Cookie", "sClick=true; JSESSIONID=0000VqEF1LT7reBRc7nDwQpbueh:-1");

                // 执行HttpPost请求
                CloseableHttpResponse response = httpClient.execute(post);
                try {
                    // 检查响应状态码是否为200（OK）
                    if (response.getStatusLine().getStatusCode() == 200) {
                        HttpEntity entity = response.getEntity();
                        // 如果响应实体不为空
                        if (entity != null) {
                            // TODO: 将数据处理后存放在Excel中
                            System.out.println(EntityUtils.toString(entity, "UTF-8"));
                        }
                    }else {
                        //存放Excel中，如果成功，则填写内容，如果不成功，则填充error
                        System.err.println("请求失败，状态码：" + response.getStatusLine().getStatusCode());
                    }
                } finally {
                    // 关闭响应
                    response.close();
                    // 打印睡眠信息
                    System.out.println("随机睡眠1-10s，防止自动化获取失败-------------------------------------------------------------------------------------------------");

                    // 随机睡眠1-10秒
                    sleep((long) (Math.random() * 10000));
                    // 打印睡眠结束信息
                    System.out.println("睡眠结束");
                    // 更新起始位置，准备获取下一页数据
                    start += limit;
                    System.out.println();
                }
            } catch (Exception e) {
                // 抛出运行时异常
                throw new RuntimeException(e);
            }
        }
    }
}
